using System;
using System.IO;
using System.Web;

namespace LocalBoard.Web
{
	/// <summary>
	/// Summary description for FileUploadController.
	/// </summary>
	public class FileUploadController
	{
		private string _folderPath = "";

		public FileUploadController(string folderPath)
		{
			_folderPath = folderPath;
		}

		public string WriteUploadedPhotoFile(HttpPostedFile photoFile)
		{
			return WriteUploadedPhotoFile(photoFile, "", false);
		}
		public string WriteUploadedPhotoFile(HttpPostedFile photoFile, string filenameToReplace)
		{
			return WriteUploadedPhotoFile(photoFile, filenameToReplace, true);
		}
		public string WriteUploadedPhotoFile(HttpPostedFile photoFile, bool overwrite)
		{
			return WriteUploadedPhotoFile(photoFile, "", overwrite);
		}
		public string WriteUploadedPhotoFile(HttpPostedFile photoFile, string filenameToReplace, bool overwrite)
		{
			if(photoFile == null)
				throw new ArgumentNullException("photoFile");

			int photoSize = photoFile.ContentLength;
			byte[] photoBuffer = new byte[photoSize];
			photoFile.InputStream.Read(photoBuffer, 0, photoSize);

			string fileNameWoExtension = filenameToReplace != null && filenameToReplace.Length > 0 ? filenameToReplace : Path.GetFileNameWithoutExtension(photoFile.FileName);
			return WriteToFile(GetPhotoPath(fileNameWoExtension, Path.GetExtension(photoFile.FileName), overwrite), ref photoBuffer);
		}

		private string WriteToFile(string strPath, ref byte[] buffer)
		{
			using(FileStream newFile = new FileStream(HttpContext.Current.Server.MapPath(strPath), FileMode.Create))
			{
				newFile.Write(buffer, 0, buffer.Length);
			}
			return strPath;
		}

		private string GetPhotoPath(string filenameWOExt, string extension, bool overwrite)
		{
			string photoFullPath = "";
			string tempPath = _folderPath + filenameWOExt + extension;
			if(overwrite) return tempPath;

			for(int i=1;i<100;i++)
			{
				if(!File.Exists(tempPath))
				{
					photoFullPath = tempPath;
					break;
				}
				else
				{
					tempPath = _folderPath + filenameWOExt + i.ToString() + extension;
				}
			}
			return photoFullPath;
		}
	}
}
